package com.example.study_manger.service;

import com.example.study_manger.entity.Organization;
import com.example.study_manger.repository.OrganizationRe;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import jakarta.persistence.criteria.Predicate;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

@Service
public class OrganizationService {
    @Autowired
    private OrganizationRe organizationRe;

    public List<Organization> getAllOrganizations() {
         return organizationRe.findAll();
    }
    private static final String apiKey = "6e7bdace-3588-4948-a51e-4f017e819456";
    private static final ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS);
    private static final Dispatcher dispatcher = new Dispatcher();
    private static final ArkService service = ArkService.builder()
            .dispatcher(dispatcher)
            .connectionPool(connectionPool)
            .baseUrl("https://ark.cn-beijing.volces.com/api/v3")
            .apiKey(apiKey)
            .build();

    /**
     * 向 Ark AI 提问并获取答案
     *
     * @param question 用户提出的问题
     * @param modelId 使用的模型ID
     * @return AI 的回答
     */
    public  String getAiResponse(String question, String modelId) {
        // 创建消息列表
        List<ChatMessage> messages = new ArrayList<>();

        // 创建用户提问的消息
        ChatMessage userMessage = ChatMessage.builder()
                .role(ChatMessageRole.USER)  // 设置角色为用户
                .content(question)  // 设置问题内容
                .build();

        // 将用户消息加入消息列表
        messages.add(userMessage);

        // 创建 ChatCompletionRequest 请求
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model(modelId)  // 使用模型ID
                .messages(messages)  // 设置用户消息
                .build();
        try {
            // 获取 AI 回复
            return (String) service.createChatCompletion(chatCompletionRequest)
                    .getChoices().get(0).getMessage().getContent();  // 获取第一条回复
        } catch (Exception e) {
            e.printStackTrace();
            return "发生错误：无法获取AI的回答。";
        } finally {
            // 关闭服务
            service.shutdownExecutor();
        }
    }

    /**
     * @param question 用户提出的问题
     * @return AI 的回答
     */
    public  String getAiResponse(String question) {
        String defaultModelId = "ep-20241228181309-w5hg8";  // 默认模型ID
        return getAiResponse(question, defaultModelId);
    }
    public Page<Organization> getOrganizations(String name,String type,int page, int size) {
        PageRequest pageRequest = PageRequest.of(page-1, size);
        Specification<Organization> specification = (Specification<Organization>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (name != null && !name.isEmpty()) {
                predicates.add(criteriaBuilder.like(root.get("name"), "%" + name + "%"));
            }
            if (type != null && !type.isEmpty()) {
                predicates.add(criteriaBuilder.like(root.get("type"), "%" + type + "%"));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };
        Page<Organization> all = organizationRe.findAll(specification,pageRequest);
        System.out.println(all.getContent());
        return all;
    }

    public Organization createOrganization(Organization organization) {
        return organizationRe.save(organization);
    }

    public Organization updateOrganization(Long id, Organization organization) {
        if (organizationRe.existsById(id)) {
            organization.setId(id);
            return organizationRe.save(organization);
        }
        return null;
    }

    public String deleteOrganization(Long id) {
        try {
            organizationRe.deleteById(id);
            return "删除成功";
        }catch (Exception e){
            return e.getMessage();
        }
    }
}
